package com.huizhan.web.controller;
 
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import io.swagger.annotations.*;
import net.bytebuddy.dynamic.scaffold.TypeWriter.FieldPool.Record;

import javax.persistence.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.text.SimpleDateFormat;

import javax.servlet.http.HttpServletRequest;

import java.util.*;

import com.huizhan.web.dao.*;
import com.huizhan.web.model.*;
import com.huizhan.web.view.*;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;

/**
 * 闸机接口
 */ 
@Api(tags = "gate",description = "闸机接口")
@RestController
public class GateController {
    @Value("${uploadFile.location}")
    private String uploadFileLocation;//上传文件保存的本地目录，使用@Value获取全局配置文件中配置的属性值
    
    @Value("${uploadFile.resourceHandler}")
    private String resourceHandler;//请求 url 中的资源映射，不推荐写死在代码中，最好提供可配置，如 /uploadFiles/**

    
    @Autowired
    private DocumentDao docDao;

    @Autowired
    private DocumentTypeDao daoD;

    @Autowired
    private ProjectDao dao;
    
    @Autowired
    private TicketTypeDao daoT;
    
    @Autowired
    private TicketDao ticDao;
   
    @Autowired
    private AccessRecordDao accDao;
    
    @Autowired
    private ProjectDoorDao doorDao;
    
    @Autowired
    private ProjectAvatarDao avatarDao;
     
    @Autowired
    private TicketComplimentaryDao tcDao;    
     
    private  static final HashMap<String,Object> defaultData=getDefault();

    private static HashMap<String,Object> getDefault(){
        HashMap<String,Object> data   = new HashMap<String,Object>();
        data.put("pId", "");
        data.put("cardno", "");
        data.put("name", "");
        data.put("company", "");
        data.put("faceUrl", "");
        data.put("historyRecord", new ArrayList<com.huizhan.web.view.Record>());

        return data;
    } 

    /**
     * 闸机程序获取 token 接口 
     * @return api结果
     */
    @ApiOperation(value = "闸机程序获取 token 接口") 
    @RequestMapping(value =  "/api/v1/GetToken",method = {RequestMethod.GET})
    public String GetToken(@RequestHeader(value="pass") String pass){
        String result="{\"msg\":\"验证成功\",\"success\":true,\"data\":{\"status\":200}}";
        return  result;
    }


    private String getId(String id){
        StringBuilder sb = new StringBuilder(id);
        sb.insert(8, "-");
        sb.insert(13, "-");
        sb.insert(18, "-");
        sb.insert(23, "-");
        return sb.toString();
    }

    /**
     * 闸机配置获取接口
     * @return api结果
     */
    @ApiOperation(value = "闸机配置获取接口")
    @RequestMapping(value = "/emaster-api/v1/gate/config" ,method = {RequestMethod.GET})
    public HashMap<String,Object> Get(@RequestHeader(value="Authorization") String authorization,@RequestHeader(value="eId") String eId,
        HttpServletResponse response){  
             HashMap<String,Object> result=new HashMap<String,Object>();
        
        try
        {
            eId=getId(eId);
            Project model= dao.getOne(eId);
            result.put("banner", model.getUrl());
            result.put("model", "1111");
            result.put("time", model.DateString());       
        }catch(Exception e){
            result.put("code", "INTERNAL_SERVER_ERROR");    
            result.put("message", "项目id不正确");    
            response.setStatus(HttpServletResponse.SC_CREATED);
        }

        return  result;
    }
    
    /**
     * 闸机条码验证接口 
     * @return api结果
     */
    @ApiOperation(value = "闸机条码验证接口")
    @RequestMapping(value =  "/emaster-api/v1/gate/validation",method = {RequestMethod.GET})
    public HashMap<String,Object> Validation (@RequestHeader(value="Authorization") String authorization,@RequestHeader(value="eId") String eId, String cardno , String deviceId ){
        HashMap<String,Object> result=new HashMap<String,Object>();

        try 
        {
            eId=getId(eId);

            if(cardno.length()==36){

                Ticket ticket=ticDao.findByProjectIdAndIdNumber(eId, cardno);

                if(ticket!=null){
                    ArrayList<com.huizhan.web.view.Record> list=new ArrayList<com.huizhan.web.view.Record>();
                    
                    List<AccessRecord> records=accDao.findByProjectIdAndCode(eId, cardno);
                    
                    for (AccessRecord accessRecord : records) {
                        com.huizhan.web.view.Record r = new com.huizhan.web.view.Record();
                        r.setEntryTime(accessRecord.getCreateDate().toString());
                        r.setPosition(accessRecord.getDoor());
                        list.add(r);
                    }

                    if(ticket.getIsPassage()==1){

                         result.put("success", false);
                         result.put("msg", "票已经通行");
                         HashMap<String,Object> data=new HashMap<String,Object>();
                         result.put("data", data);
                         data.put("pId", ticket.getTicketId().toString());
                         data.put("cardno", cardno);
                         data.put("name", ticket.getName());
                         data.put("company", "");
                         data.put("faceUrl", ticket.getAvatar());
                         data.put("historyRecord", list);
                     }else{
                         try {
                            if(ticket.getTicketComplimentaryId()!=null&&ticket.getTicketComplimentaryId()>0){
                                TicketComplimentary complimentary=tcDao.getOne(ticket.getTicketComplimentaryId());
                                complimentary.setUseNumber(complimentary.getUseNumber()+1);
                                tcDao.save(complimentary);
                            }
                         } catch (Exception e) {
                         }

                         ticket.setIsPassage(1);
                         ticket.setSignDate(new Date());
                         ticDao.save(ticket);
                         
                         result.put("success", true);
                         result.put("msg", "验证成功");
                         HashMap<String,Object> data=new HashMap<String,Object>();
                         result.put("data", data);
                         data.put("pId", ticket.getTicketId().toString());
                         data.put("cardno", cardno);
                         data.put("name", ticket.getName());
                         data.put("company", "");
                         data.put("faceUrl", ticket.getAvatar());
                         data.put("historyRecord", list);
                     }
                }else{
                    result.put("success", false);
                    result.put("msg", "无效票证");
                    result.put("data", defaultData); 
                }
            }else{
                Document document= docDao.findByProjectIdAndCode(eId,cardno);

                if(document!=null){
                    
                   DocumentType type=daoD.getOne(document.getDocumentTypeId());

                   Integer count= accDao.countByProjectIdAndCode(eId, cardno);

                   if(count>0&& count>Integer.parseInt(type.getRule()) ){
                        result.put("success", false);
                        result.put("msg", "证件今日通行已达限定次数");
                        result.put("data", defaultData); 
                   }else{
                        ArrayList<com.huizhan.web.view.Record> list=new ArrayList<com.huizhan.web.view.Record>();
                        
                        List<AccessRecord> records=accDao.findByProjectIdAndCode(eId, cardno);
                        
                        for (AccessRecord accessRecord : records) {
                            com.huizhan.web.view.Record r = new com.huizhan.web.view.Record();
                            r.setEntryTime(accessRecord.getCreateDate().toString());
                            r.setPosition(accessRecord.getDoor());
                            list.add(r);
                        }

                        result.put("success", true);
                        result.put("msg", "验证成功");
                        HashMap<String,Object> data=new HashMap<String,Object>();
                        result.put("data", data);
                        data.put("pId", document.getDocumentId().toString());
                        data.put("cardno", cardno);
                        data.put("name", document.getName());
                        data.put("company", "");
                        data.put("faceUrl", document.getAvatar());
                        data.put("historyRecord", list);
                   }
                }else{
                    result.put("success", false);
                    result.put("msg", "无效票证");
                    result.put("data", defaultData); 
                }
            }
        }catch(Exception e){ 
            result.put("success", false);
            result.put("msg", "无效票证");
            result.put("data", defaultData); 
        }
        return  result;
    }

    /**
     * 更新人脸接口  
     * @return api结果
     */
    @ApiOperation(value = "更新人脸接口")
    @RequestMapping(value =  "/emaster-api/v1/gate/face",method = {RequestMethod.POST})
    public void Face(@RequestHeader(value="Authorization") String authorization, @RequestHeader(value="eId") String eId ,String pId,String base64Img,
        HttpServletRequest request,
        HttpServletResponse response){
        
        try 
        {
            eId=getId(eId);
            Optional<Document> document= docDao.findById(Long.parseLong(pId));

            if(document.isPresent()){
                   
                Base64String bString=new Base64String();
                bString.setBase64(base64Img);

                String newFilePath=bString.getFileName();

                File file=new File(uploadFileLocation+newFilePath);

                if(!file.exists()){
                    Util.base64ToImage(bString.getBase64(), uploadFileLocation+newFilePath);        
                }

                document.get().setAvatar(request.getScheme() + "://" + request.getServerName() +"/upload/"+newFilePath);;

                docDao.save(document.get());

                ProjectAvatar avatar=new ProjectAvatar();

                avatar.setCode(document.get().getCode());
                avatar.setCreateDate(new Date());
                avatar.setDocumentId(document.get().getDocumentId());
                avatar.setDocumentTypeId(document.get().getDocumentTypeId());
                avatar.setName(document.get().getName());
                avatar.setProjectId(document.get().getProjectId());
                avatar.setUrl(document.get().getAvatar());

                avatarDao.save(avatar);
            }else{
                /*Optional<Ticket> ticket=ticDao.findById(Long.parseLong(pId));

                if(ticket.isPresent()){
                    ticket.get().setAvatar(request.getScheme() + "://" + request.getServerName() +"/upload/"+newFilePath);;
    
                    ticDao.save(ticket.get());
                }*/
            }
        }catch(Exception e){
            
        }
        
        response.setStatus(HttpServletResponse.SC_CREATED);
    }
    
    /**
     * 入场增加记录接口  
     * @return api结果
     */
    @ApiOperation(value = "入场增加记录接口")
    @RequestMapping(value =   "/emaster-api/v1/gate/record",method = {RequestMethod.POST})
    public void Record (@RequestHeader(value="Authorization") String authorization,@RequestHeader(value="eId") String eId ,String pId, String deviceId,String cardno,String time,
        HttpServletRequest request,
        HttpServletResponse response){ 
        
        try 
        {
            eId=getId(eId);
            ProjectDoor door = doorDao.findByProjectIdAndName(eId,deviceId);
            Document document= docDao.findByProjectIdAndCode(eId,cardno);
            AccessRecord record=new AccessRecord();

            record.setCode(cardno);
            record.setCreateDate(new Date());

            if(door!=null){
                record.setProjectDoorId(door.getProjectDoorId());
                record.setDoor(door.getName());
            }

            if(document!=null){
                DocumentType type = daoD.getOne(document.getDocumentTypeId());

                record.setTypeName(type.getName());
                record.setName(document.getName());
                record.setAvatar(document.getAvatar());
                record.setDocumentId(document.getDocumentId());
                record.setDocumentTypeId(document.getDocumentTypeId());
                record.setIdNumber(document.getIdNumber());
                record.setProjectId(eId);
                record.setName(document.getName());
                record.setDoor(deviceId);
                record.setCode(document.getCode());
                accDao.save(record);
            }else{
               Ticket ticket=ticDao.findByProjectIdAndIdNumber(eId, cardno);
               
               if(ticket!=null){
                    TicketType type = daoT.getOne(ticket.getTicketTypeId());

                    record.setTypeName(type.getName());
                    record.setName(ticket.getName());
                    record.setTicketId(ticket.getTicketId());
                    record.setTicketTypeId(ticket.getTicketTypeId());
                    record.setIdNumber(ticket.getIdNumber());
                    record.setProjectId(eId);
                    record.setName(ticket.getName());
                    record.setDoor(deviceId);
                    record.setCode(ticket.getCode());
                    accDao.save(record);
               }else{
                   
               }
           }
        }catch(Exception e){
            
        }
 
        response.setStatus(HttpServletResponse.SC_CREATED);
    }
    
    /**
     * 离线入场信息回传接口
     * @return api结果
     */
    @ApiOperation(value = "离线入场信息回传接口 ")
    @RequestMapping(value ="/emaster-api/v1/gate/oﬄineRecord",method = {RequestMethod.POST})
    public void OﬄineRecord  (@RequestHeader(value="Authorization") String authorization,@RequestHeader(value="eId") String eId , String pId, String deviceId,String base64Img,String cardno,String time,
        HttpServletRequest request,
        HttpServletResponse response){
       
        try 
        {
            eId=getId(eId);
            ProjectDoor door=  doorDao.findByProjectIdAndDeviceLike(eId,deviceId);
            Document document= docDao.findByProjectIdAndCode(eId,cardno);
            AccessRecord record=new AccessRecord();

            Base64String bString=new Base64String();
            bString.setBase64(base64Img);

            String newFilePath=bString.getFileName();

            File file=new File(uploadFileLocation+newFilePath);

            if(!file.exists()){
                Util.base64ToImage(bString.getBase64(), uploadFileLocation+newFilePath);        
            }

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            record.setCode(cardno);
            record.setCreateDate(sdf.parse(time));
            record.setAvatar(request.getScheme() + "://" + request.getServerName() +"/upload/"+newFilePath);;

            if(door!=null){
                record.setProjectDoorId(door.getProjectDoorId());
                record.setDoor(door.getName());
            }

            if(document!=null){
                record.setName(document.getName());
                record.setAvatar(document.getAvatar());
                record.setDocumentId(document.getDocumentId());
                record.setDocumentTypeId(document.getDocumentTypeId());
                record.setIdNumber(document.getIdNumber());
                record.setProjectId(eId);
                accDao.save(record);
            }else{
               Ticket ticket=ticDao.findByProjectIdAndIdNumber(eId, cardno);

               if(ticket!=null){
                  
                record.setName(ticket.getName());
                record.setAvatar(ticket.getAvatar());
                record.setTicketId(ticket.getTicketId());
                record.setTicketTypeId(ticket.getTicketTypeId());
                record.setIdNumber(ticket.getIdNumber());
                record.setProjectId(eId);
                accDao.save(record);
               }else{
                   
               }
           }
        }catch(Exception e){
            
        }
        response.setStatus(HttpServletResponse.SC_CREATED);
    }
}